// pages/lists/lists.js
var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    pagination: {
      page: 1,
      total: 0
    },
    blogList: [],
    loadMore: true,
    ptypeId: '', //分类id
    kinds: [{
        icon: 'icon-gou',
        name: '前端',
        ptypeId: '1'
      }, {
        icon: 'icon--niuroulei',
        name: '后端',
        ptypeId: '2'
      },
      {
        icon: 'icon-tuzi',
        name: '综合',
        ptypeId: '3'
      }
    ]
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // var typeId = options.typeId;
    // this.setData({
    //   typeId: typeId,
    // })
    wx.showLoading();
    this.getLists();
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    var pagination = this.data.pagination;
    pagination.page = pagination.page + 1;
    this.setData({
      pagination: pagination,
      blogList: [],
      loadMore: true
    });
    this.getLists();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var that = this,
      pagination = this.data.pagination;
    pagination.page = pagination.page + 1;
    if (that.data.loadMore) {
      that.setData({
        pagination: pagination
      })
      that.getLists();
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {
      title: '锲而舍之,朽木不折;锲而不舍,金石可镂',
      imageUrl: '/assets/images/share.jpg'
    }
  },
  articleDetail: function(e) {
    let blogId = e.currentTarget.dataset.blogid;
    wx.navigateTo({
      url: '../detail/detail?blogId=' + blogId
    })
  },
  showOne: function(e) {
    let ptypeId = e.currentTarget.dataset.ptypeid,
      pagination = this.data.pagination;
    if (ptypeId != this.data.ptypeId) {
      pagination.page = 1;
      this.setData({
        ptypeId: ptypeId,
        blogList: [],
        pagination: pagination,
        loadMore: true
      });
      this.getLists();
    } 
  },
  onPageScroll: function(e) {
    if (e.scrollTop > 100) {
      this.setData({
        backShow: true
      });
    } else {
      this.setData({
        backShow: false
      });
    }
  },
  getLists: function(e) {
    if (this.data.loadMore) {
      var that = this,
        pagination = this.data.pagination;
      let params = {
        page: that.data.pagination.page,
        ptypeId: that.data.ptypeId
      }
      util.reqNoAuth(api.BlogList, params).then(function(res) {
        if (res.code === 0) {
          let _items = that.data.blogList.concat(res.dataList);
          that.setData({
            blogList: _items
          });
          if (pagination.page >= res.pagination.totalPage) {
            that.setData({
              loadMore: false
            })
          }
        }
      });
      wx.hideLoading();
    }
  }
})